package com.hujing;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

public class DeadLockDemo1 {


    public static void main(String[] args) {
        DinnerThread dinnerThread = new DinnerThread();
        new Thread(dinnerThread, "jack").start();
        new Thread(dinnerThread, "rose").start();
    }

}

class DinnerThread implements Runnable {

    private final ConcurrentHashMap<String, ReentrantLock> lockMap = new ConcurrentHashMap<>();

    String lock1 = "第1根筷子";
    String lock2 = "第2根筷子";

    @Override
    public void run() {
        String key = Thread.currentThread().getName();
        ReentrantLock lock = lockMap.computeIfAbsent(key, k -> new ReentrantLock());
        lock.lock();
        try {
            System.out.println("Jack拿到" + lock2);
            System.out.println(Thread.currentThread().getName() + "开始夹东西吃");
        }finally {
            lock.unlock();
        }
//        if (Thread.currentThread().getName().equals("jack")){
//            synchronized (lock1){
//                System.out.println("Jack拿到"+lock1);
//                synchronized (lock2){
//                    System.out.println("Jack拿到"+lock2);
//                    System.out.println(Thread.currentThread().getName()+"开始夹东西吃");
//                }
//            }
//        }else{
//            synchronized (lock2){
//                System.out.println("Rose拿到"+lock2);
//                synchronized (lock1){
//                    System.out.println("Rose拿到"+lock1);
//                    System.out.println(Thread.currentThread().getName()+"开始夹东西吃");
//                }
//            }
//        }
    }
}
